package br.ufc.dc.redes.proxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/** Ler argumentos da linha de comando e inicia o proxy */
public class Main {
	public static ServerSocket init(int port) throws IOException {
		return new ServerSocket(port);
	}

	public static void main(String args[]) {
		int myPort = 8787;
		try {
			ServerSocket socket = init(myPort);

			Socket client = null;

			while (true) {
				try {
					
					client = socket.accept();
					System.out.println("Got connection " + client);
					new Thread(new ProxyCacheThread(client)).start();
					
				} catch (IOException e) {
					System.out.println("Error reading request from client: "
							+ e);
					continue;
				}
			}
		} catch (IOException e) {
			System.out.println("Error initializing server");
			e.printStackTrace();
			System.exit(1);
		}

	}
}

class ProxyCacheThread implements Runnable {
	private Socket client = null;

	public ProxyCacheThread(Socket socket) {
		this.client = socket;
	}

	@Override
	public void run() {
		try {
			ProxyCache.handle(client);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
